package stackoverflow.data.repositoryimpl;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import stackoverflow.domain.user.User;
import stackoverflow.domain.user.UserRepository;

@Repository("userRepositoryImpl")
public class UserRepositoryImpl extends HibernateRepository implements
		UserRepository {

	@Autowired
	public UserRepositoryImpl
	(@Qualifier("sessionFactory") SessionFactory sessionFactory) {
		this.sessionFactory = sessionFactory;
	}

	@Transactional(propagation=Propagation.REQUIRED)
	public User find(String userId) {
		Session session;
		Query query;
		try 
		{
			session = sessionFactory.getCurrentSession();
			query = session.getNamedQuery("findUserById");
			//query.setBinary("id", userId);
			return (User) query.uniqueResult(); // returns null if no results
		}
		catch (DataAccessException e) {
			throw new IllegalArgumentException("Could not find user.");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}

	public List<User> findAll() {
		// TODO Auto-generated method stub
		return null;
	}

	public void store(User user) {
		Session session = sessionFactory.getCurrentSession();
		session.save(user);
	}

	public User findByName(String userName) {
		Session session;
		Query query;
		try 
		{
			session = sessionFactory.getCurrentSession();
			query = session.getNamedQuery("findUserByName");
			query.setString("userName", userName);
			return (User) query.uniqueResult(); // returns null if no results
		}
		catch (DataAccessException e) {
			throw new IllegalArgumentException("Could not find user.");
		}
		catch(Exception e)
		{
			e.printStackTrace();
		}
		return null;
	}
}
